<template>
  <div class="user-profile">
    <div class="profile-header">
      <h2>个人信息</h2>
      <p>管理您的个人资料和账户设置</p>
    </div>

    <el-row :gutter="24">
      <!-- 左侧：头像和基本信息 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar
                :size="120"
                :src="getAvatarUrl(userInfo.avatar)"
                class="profile-avatar"
              >
                {{ userInfo.username?.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="avatar-overlay" @click="triggerUpload">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
            
            <!-- 头像上传组件 -->
            <el-upload
              ref="uploadRef"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              accept="image/*"
              class="avatar-upload"
            >
              <el-button type="primary" size="small" class="upload-btn">
                <el-icon><Upload /></el-icon>
                选择图片
              </el-button>
            </el-upload>
            
            <div class="upload-tips">
              <p>支持 JPG、PNG 格式</p>
              <p>文件大小不超过 2MB</p>
            </div>
          </div>

          <div class="user-summary">
            <h3>{{ userInfo.username }}</h3>
            <el-tag :type="getRoleTagType()" size="small">
              {{ getRoleText() }}
            </el-tag>
            <p class="join-date">
              加入时间：{{ formatDate(userInfo.date_joined) }}
            </p>
          </div>

          <!-- 个性化设置 -->
          <div class="personalization-section">
            <h4>个性化设置</h4>

            <!-- 背景类型选择 -->
            <div class="setting-item">
              <label>用户卡片背景：</label>
              <el-radio-group v-model="backgroundType" @change="handleBackgroundTypeChange" size="small">
                <el-radio value="none">无背景</el-radio>
                <el-radio value="preset">预设</el-radio>
                <el-radio value="custom">自定义</el-radio>
              </el-radio-group>
            </div>

            <!-- 预设背景选择 -->
            <div v-if="backgroundType === 'preset'" class="preset-backgrounds">
              <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange" size="small">
                <el-tab-pane
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :name="category.id"
                >
                  <div class="background-grid">
                    <div
                      v-for="preset in getPresetsByCategory(category.id)"
                      :key="preset.id"
                      class="background-option"
                      :class="{ active: selectedPreset === preset.id }"
                      @click="selectPreset(preset.id)"
                    >
                      <div class="preview" :style="{ background: preset.preview }"></div>
                      <span class="name">{{ preset.name }}</span>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>

            <!-- 自定义上传 -->
            <div v-if="backgroundType === 'custom'" class="custom-upload">
              <el-upload
                class="background-uploader"
                :show-file-list="false"
                :before-upload="beforeBackgroundUpload"
                :on-success="handleBackgroundSuccess"
                :on-error="handleBackgroundError"
                :action="backgroundUploadUrl"
                :headers="uploadHeaders"
                name="background"
              >
                <div class="upload-area" v-if="!customBackgroundUrl">
                  <el-icon><Plus /></el-icon>
                  <div class="upload-text">点击上传背景图片</div>
                  <div class="upload-hint">支持 JPG/PNG，建议尺寸 400x200px，最大 2MB</div>
                </div>
                <div class="uploaded-background" v-else>
                  <img :src="customBackgroundUrl" alt="自定义背景" />
                  <div class="upload-overlay">
                    <el-icon><Edit /></el-icon>
                    <span>更换背景</span>
                  </div>
                </div>
              </el-upload>
            </div>

            <!-- 实时预览 -->
            <div class="background-preview">
              <label>预览效果：</label>
              <div class="preview-card" :style="getPreviewStyle()">
                <el-avatar :size="32" :src="getAvatarUrl(userInfo.avatar)">
                  {{ displayName.charAt(0).toUpperCase() }}
                </el-avatar>
                <div class="preview-info">
                  <div class="preview-name">{{ displayName }}</div>
                  <div class="preview-email">{{ userInfo.email || '未设置邮箱' }}</div>
                  <el-tag size="small" type="success">{{ getUserRoleText() }}</el-tag>
                </div>
              </div>
            </div>

            <!-- 保存按钮 -->
            <div class="setting-actions">
              <el-button
                type="primary"
                size="small"
                @click="saveBackgroundSettings"
                :loading="savingBackground"
              >
                保存背景设置
              </el-button>
              <el-button size="small" @click="resetBackgroundSettings">重置</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：详细信息编辑 -->
      <el-col :span="16">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button
                v-if="hasEditableFields"
                type="primary"
                size="small"
                @click="toggleEdit"
                :loading="saving"
              >
                {{ isEditing ? '保存' : getEditButtonText() }}
              </el-button>
              <el-tag v-else type="info" size="small">
                仅查看模式
              </el-tag>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            class="profile-form"
          >
            <!-- 系统信息区 -->
            <div class="system-section">
              <el-divider content-position="left">
                <span class="section-title">系统信息</span>
              </el-divider>

              <!-- 用户名（所有用户都不可编辑） -->
              <el-form-item label="用户名">
                <el-input
                  v-model="formData.username"
                  disabled
                  placeholder="系统用户名"
                >
                  <template #suffix>
                    <el-icon class="readonly-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 邮箱（根据权限决定是否可编辑） -->
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="formData.email"
                  :disabled="!canEditField('email')"
                  placeholder="联系邮箱"
                  type="email"
                >
                  <template #suffix>
                    <el-icon v-if="!canEditField('email')" class="readonly-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 姓名（根据权限决定是否可编辑） -->
              <el-form-item label="姓名" prop="full_name">
                <el-input
                  v-model="formData.full_name"
                  :disabled="!canEditField('full_name')"
                  placeholder="真实姓名"
                >
                  <template #suffix>
                    <el-icon v-if="!canEditField('full_name')" class="readonly-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 手机号（根据权限决定是否可编辑） -->
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="formData.phone"
                  :disabled="!canEditField('phone')"
                  placeholder="联系电话"
                >
                  <template #suffix>
                    <el-icon v-if="!canEditField('phone')" class="readonly-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>



              <!-- 权限提示 -->
              <el-alert
                v-if="userInfo.is_superuser"
                title="您是超级管理员，可以编辑除用户名外的所有信息"
                type="success"
                :closable="false"
                show-icon
                class="admin-notice"
              />

              <el-alert
                v-else-if="userInfo.is_staff"
                title="您是管理员，可以编辑部分个人信息"
                type="warning"
                :closable="false"
                show-icon
                class="admin-notice"
              />

              <el-alert
                v-else
                title="您可以编辑个人简介，其他信息如需修改请联系系统管理员"
                type="info"
                :closable="false"
                show-icon
                class="admin-notice"
              />
            </div>

            <!-- 用户可编辑的字段 -->
            <div class="editable-section">
              <el-divider content-position="left">
                <span class="section-title">个人资料（可编辑）</span>
              </el-divider>

              <el-form-item label="个人简介" prop="bio">
                <el-input
                  v-model="formData.bio"
                  :disabled="!isEditing"
                  type="textarea"
                  :rows="4"
                  placeholder="介绍一下自己..."
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </el-form>
        </el-card>

        <!-- 密码修改卡片 -->
        <el-card class="password-card" style="margin-top: 20px;">
          <template #header>
            <span>密码设置</span>
          </template>

          <el-button
            type="warning"
            @click="showPasswordDialog = true"
            :icon="Lock"
          >
            修改密码
          </el-button>
        </el-card>


      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="passwordFormRef" 
        :model="passwordForm" 
        :rules="passwordRules" 
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="old_password">
          <el-input 
            v-model="passwordForm.old_password" 
            type="password" 
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="new_password">
          <el-input 
            v-model="passwordForm.new_password" 
            type="password" 
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirm_password">
          <el-input 
            v-model="passwordForm.confirm_password" 
            type="password" 
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="changePassword"
          :loading="changingPassword"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, Upload, Lock, Plus, Edit } from '@element-plus/icons-vue'
import { authAPI } from '../../api/auth'
import eventBus, { EVENT_NAMES } from '../../utils/eventBus'
import { backgroundPresets, getPresetsByCategory, getPresetById, getCategories } from '../../config/backgroundPresets'

// 响应式数据
const userInfo = ref({})
const isEditing = ref(false)
const saving = ref(false)
const showPasswordDialog = ref(false)
const changingPassword = ref(false)
const uploadRef = ref()
const formRef = ref()
const passwordFormRef = ref()

// 背景设置相关数据
const backgroundType = ref('none')
const selectedPreset = ref('')
const activeCategory = ref('gradient')
const customBackgroundUrl = ref('')
const savingBackground = ref(false)
const categories = ref(getCategories())

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  full_name: '',
  phone: '',
  bio: ''
})

// 密码表单
const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

// 上传配置
const uploadUrl = computed(() => {
  // 使用与API相同的逻辑获取基础URL
  const protocol = window.location.protocol
  const hostname = window.location.hostname

  let baseUrl
  if (import.meta.env.DEV && hostname === 'localhost') {
    baseUrl = 'http://localhost:8000'
  } else {
    baseUrl = `${protocol}//${hostname}:8000`
  }

  return `${baseUrl}/api/auth/upload-avatar/`
})

const uploadHeaders = computed(() => {
  return {
    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
  }
})

// 背景上传URL
const backgroundUploadUrl = computed(() => {
  const protocol = window.location.protocol
  const hostname = window.location.hostname

  let baseUrl
  if (import.meta.env.DEV && hostname === 'localhost') {
    baseUrl = 'http://localhost:8000'
  } else {
    baseUrl = `${protocol}//${hostname}:8000`
  }

  return `${baseUrl}/api/auth/upload-background/`
})

// 显示名称
const displayName = computed(() => {
  return userInfo.value.full_name || userInfo.value.username || '未知用户'
})

// 表单验证规则（根据权限动态验证）
const formRules = computed(() => {
  const rules = {
    bio: [
      { max: 500, message: '个人简介不能超过500个字符', trigger: 'blur' }
    ]
  }

  // 超级管理员和管理员可以编辑更多字段
  if (userInfo.value.is_superuser || userInfo.value.is_staff) {
    rules.email = [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
    rules.full_name = [
      { required: true, message: '请输入真实姓名', trigger: 'blur' }
    ]
    rules.phone = [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }



  return rules
})

const passwordRules = {
  old_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const loadUserInfo = async () => {
  try {
    const response = await authAPI.getUserProfile()
    userInfo.value = response

    // 填充表单数据
    Object.keys(formData).forEach(key => {
      formData[key] = response[key] || ''
    })

    // 初始化背景设置
    initializeBackgroundSettings()
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

const getRoleText = () => {
  if (userInfo.value.is_superuser) {
    return '超级管理员'
  } else if (userInfo.value.is_staff) {
    return '管理员'
  } else {
    return '普通用户'
  }
}

const getRoleTagType = () => {
  if (userInfo.value.is_superuser) {
    return 'danger'
  } else if (userInfo.value.is_staff) {
    return 'warning'
  } else {
    return 'info'
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getAvatarUrl = (avatar) => {
  if (!avatar) return null

  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http')) {
    return avatar
  }

  // 构建完整的URL
  const protocol = window.location.protocol
  const hostname = window.location.hostname

  let baseUrl
  if (import.meta.env.DEV && hostname === 'localhost') {
    baseUrl = 'http://localhost:8000'
  } else {
    baseUrl = `${protocol}//${hostname}:8000`
  }

  return `${baseUrl}${avatar}`
}

// 检查用户是否有可编辑的字段
const hasEditableFields = computed(() => {
  // 超级管理员可以编辑除用户名外的所有字段
  if (userInfo.value.is_superuser) {
    return true
  }

  // 普通管理员可以编辑部分字段
  if (userInfo.value.is_staff) {
    return true
  }

  // 普通用户可以编辑个人简介
  // 如果要完全禁用普通用户编辑，改为 return false
  return true // 普通用户可以编辑简介
})

// 获取编辑按钮文本
const getEditButtonText = () => {
  if (userInfo.value.is_superuser) {
    return '编辑个人信息'
  } else if (userInfo.value.is_staff) {
    return '编辑基本信息'
  } else {
    return '编辑简介'
  }
}

// 检查字段是否可编辑
const canEditField = (fieldName) => {
  if (!isEditing.value) return false

  // 用户名永远不可编辑
  if (fieldName === 'username') return false

  // 超级管理员可以编辑除用户名外的所有字段
  if (userInfo.value.is_superuser) {
    return ['email', 'full_name', 'phone', 'bio'].includes(fieldName)
  }

  // 普通管理员可以编辑部分字段
  if (userInfo.value.is_staff) {
    return ['email', 'full_name', 'phone', 'bio'].includes(fieldName)
  }

  // 普通用户只能编辑个人简介
  return fieldName === 'bio'
}

const triggerUpload = () => {
  uploadRef.value.$el.querySelector('input').click()
}

const toggleEdit = async () => {
  if (isEditing.value) {
    // 保存数据
    await saveProfile()
  } else {
    // 进入编辑模式
    isEditing.value = true
  }
}

const saveProfile = async () => {
  saving.value = true
  try {
    // 根据用户权限确定可提交的字段
    const editableData = {}

    if (userInfo.value.is_superuser) {
      // 超级管理员可以编辑除用户名外的所有字段
      const allowedFields = ['email', 'full_name', 'phone', 'bio']
      allowedFields.forEach(field => {
        if (formData[field] !== undefined) {
          editableData[field] = formData[field]
        }
      })
    } else if (userInfo.value.is_staff) {
      // 普通管理员可以编辑部分字段
      const allowedFields = ['email', 'full_name', 'phone', 'bio']
      allowedFields.forEach(field => {
        if (formData[field] !== undefined) {
          editableData[field] = formData[field]
        }
      })
    } else {
      // 普通用户只能编辑个人简介
      editableData.bio = formData.bio
    }

    const response = await authAPI.updateProfile(editableData)
    ElMessage.success(response.message || '个人信息更新成功')
    isEditing.value = false
    await loadUserInfo() // 重新加载用户信息

    // 触发全局事件，通知其他组件用户信息已更新
    eventBus.emit(EVENT_NAMES.USER_PROFILE_UPDATED, {
      userId: userInfo.value.id,
      updatedFields: editableData,
      userInfo: userInfo.value
    })
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  } finally {
    saving.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response) => {
  ElMessage.success('头像上传成功')

  // 确保使用完整的URL
  const avatarUrl = response.avatar_url
  userInfo.value.avatar = avatarUrl

  // 更新本地存储的用户信息
  const cachedUserInfo = JSON.parse(localStorage.getItem('user_info') || '{}')
  cachedUserInfo.avatar = avatarUrl
  localStorage.setItem('user_info', JSON.stringify(cachedUserInfo))

  // 触发全局用户信息更新事件
  window.dispatchEvent(new CustomEvent('user-info-updated', {
    detail: { ...userInfo.value, avatar: avatarUrl }
  }))

  // 强制重新渲染头像
  setTimeout(() => {
    loadUserInfo()
  }, 500)
}

const handleAvatarError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true

    await authAPI.changePassword({
      old_password: passwordForm.old_password,
      new_password: passwordForm.new_password
    })

    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false

    // 重置表单
    Object.keys(passwordForm).forEach(key => {
      passwordForm[key] = ''
    })
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error(error.response?.data?.error || '修改密码失败')
  } finally {
    changingPassword.value = false
  }
}

// 背景相关方法

const getUserRoleText = () => {
  if (userInfo.value.is_superuser) {
    return '超级管理员'
  } else if (userInfo.value.is_staff) {
    return '管理员'
  } else {
    return '普通用户'
  }
}

const handleBackgroundTypeChange = (type) => {
  backgroundType.value = type
  if (type === 'none') {
    selectedPreset.value = ''
    customBackgroundUrl.value = ''
  }
}

const handleCategoryChange = () => {
  // 切换分类时可以做一些处理
}

const selectPreset = (presetId) => {
  selectedPreset.value = presetId
  backgroundType.value = 'preset'
}

const getPreviewStyle = () => {
  if (backgroundType.value === 'none') {
    return {
      background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
    }
  }

  if (backgroundType.value === 'preset' && selectedPreset.value) {
    const preset = getPresetById(selectedPreset.value)
    return preset ? preset.style : {}
  }

  if (backgroundType.value === 'custom' && customBackgroundUrl.value) {
    return {
      backgroundImage: `url(${customBackgroundUrl.value})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center'
    }
  }

  return {
    background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
  }
}

const beforeBackgroundUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleBackgroundSuccess = (response) => {
  ElMessage.success('背景图片上传成功')
  customBackgroundUrl.value = response.background_url
  backgroundType.value = 'custom'
}

const handleBackgroundError = (error) => {
  console.error('背景图片上传失败:', error)
  ElMessage.error('背景图片上传失败，请重试')
}

const saveBackgroundSettings = async () => {
  savingBackground.value = true
  try {
    const settings = {
      type: backgroundType.value,
      preset_id: selectedPreset.value,
      opacity: 0.8,
      position: 'center'
    }

    // 使用与其他API相同的逻辑获取基础URL
    const protocol = window.location.protocol
    const hostname = window.location.hostname

    let baseUrl
    if (import.meta.env.DEV && hostname === 'localhost') {
      baseUrl = 'http://localhost:8000'
    } else {
      baseUrl = `${protocol}//${hostname}:8000`
    }

    const response = await fetch(`${baseUrl}/api/auth/background-settings/`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      },
      body: JSON.stringify(settings)
    })

    if (response.ok) {
      ElMessage.success('背景设置保存成功')
      // 重新加载用户信息
      await loadUserInfo()
      // 触发全局事件
      eventBus.emit(EVENT_NAMES.USER_PROFILE_UPDATED, {
        userId: userInfo.value.id,
        updatedFields: { background_settings: settings },
        userInfo: userInfo.value
      })
    } else {
      throw new Error('保存失败')
    }
  } catch (error) {
    console.error('保存背景设置失败:', error)
    ElMessage.error('保存背景设置失败')
  } finally {
    savingBackground.value = false
  }
}

const resetBackgroundSettings = () => {
  backgroundType.value = 'none'
  selectedPreset.value = ''
  customBackgroundUrl.value = ''
}

const initializeBackgroundSettings = () => {
  const settings = userInfo.value.background_settings || {}
  backgroundType.value = settings.type || 'none'
  selectedPreset.value = settings.preset_id || ''

  if (settings.type === 'custom' && userInfo.value.background_image) {
    customBackgroundUrl.value = userInfo.value.background_image
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-header {
  margin-bottom: 24px;
}

.profile-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.profile-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.profile-card {
  text-align: center;
}

.avatar-section {
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.profile-avatar {
  border: 4px solid #e4e7ed;
  transition: all 0.3s ease;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
  color: white;
  font-size: 12px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-container:hover .profile-avatar {
  border-color: #409eff;
}

.avatar-upload {
  margin-bottom: 12px;
}

.upload-btn {
  width: 100%;
}

.upload-tips {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.upload-tips p {
  margin: 2px 0;
}

.user-summary h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.join-date {
  margin: 12px 0 0 0;
  font-size: 13px;
  color: #909399;
}

/* 个性化设置样式 */
.personalization-section {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.personalization-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.setting-item {
  margin-bottom: 16px;
}

.setting-item label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.background-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 8px;
  margin-top: 8px;
}

.background-option {
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 6px;
  padding: 6px;
  transition: all 0.3s ease;
  text-align: center;
}

.background-option:hover {
  border-color: #409eff;
  transform: translateY(-1px);
}

.background-option.active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.background-option .preview {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  margin-bottom: 4px;
  border: 1px solid #e4e7ed;
}

.background-option .name {
  font-size: 11px;
  color: #606266;
  display: block;
}

.custom-upload {
  margin-top: 12px;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px 10px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-text {
  margin-top: 6px;
  font-size: 12px;
  color: #606266;
}

.upload-hint {
  margin-top: 2px;
  font-size: 10px;
  color: #909399;
}

.uploaded-background {
  position: relative;
  width: 120px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  margin: 0 auto;
}

.uploaded-background img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-size: 10px;
}

.uploaded-background:hover .upload-overlay {
  opacity: 1;
}

.background-preview {
  margin-top: 16px;
}

.background-preview label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.preview-card {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  position: relative;
  overflow: hidden;
}

.preview-info {
  margin-left: 8px;
  flex: 1;
}

.preview-name {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.preview-email {
  font-size: 11px;
  color: #909399;
  margin-bottom: 4px;
}

.setting-actions {
  margin-top: 16px;
  text-align: center;
}

.setting-actions .el-button {
  margin: 0 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form {
  margin-top: 20px;
}

.password-card {
  text-align: center;
}

/* 系统信息区样式 */
.system-section {
  margin-bottom: 30px;
}

.system-section .el-input.is-disabled {
  background-color: #f8f9fa;
}

/* 可编辑字段在编辑模式下的样式 */
.system-section .el-input:not(.is-disabled) {
  border-color: #409eff;
}

.system-section .el-input:not(.is-disabled):hover {
  border-color: #66b1ff;
}

.readonly-icon {
  color: #909399;
  font-size: 14px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.admin-notice {
  margin-top: 15px;
  margin-bottom: 20px;
}

.editable-section {
  margin-top: 20px;
}

.profile-form .el-form-item {
  margin-bottom: 20px;
}

/* 背景设置样式 */
.personalization-card {
  margin-top: 20px;
}

.background-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-top: 12px;
}

.background-option {
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 8px;
  padding: 8px;
  transition: all 0.3s ease;
  text-align: center;
}

.background-option:hover {
  border-color: #409eff;
  transform: translateY(-2px);
}

.background-option.active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.background-option .preview {
  width: 100%;
  height: 60px;
  border-radius: 6px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
}

.background-option .name {
  font-size: 12px;
  color: #606266;
  display: block;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.upload-hint {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.uploaded-background {
  position: relative;
  width: 200px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
}

.uploaded-background img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-size: 12px;
}

.uploaded-background:hover .upload-overlay {
  opacity: 1;
}

.background-preview {
  margin-top: 12px;
}

.preview-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  max-width: 300px;
  position: relative;
  overflow: hidden;
}

.preview-info {
  margin-left: 12px;
  flex: 1;
}

.preview-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.preview-email {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}
</style>
